export function isNetworkCanUse(callback) {
	uni.getNetworkType({
		success: res => {
			if (res.networkType === '2g' || res.networkType === 'none') {
				callback(false)
			} else {
				callback(true)
			}
		},
		fail() {
			callback(false)
		}
	})
}

export function hasNet(callback) {
	uni.onNetworkStatusChange(res => {
		callback(!res.isConnected)
	})
}

/**
 * params对象转url
 * @param {object} params
 * @param {boolean} encode
 */
export function jsonToUrlParam(json) {
	return Object.keys(json).map(key => key + '=' + json[key]).join('&')
}

/**
 * @description 刷新当前页面
 */
export const reloadPage = args => {
	const currPage = getCurrentPages().pop() // 获取所有页面的数组对象
	let isTabBar = currPage?.$page?.meta?.isTabBar
	let path = currPage?.$page?.fullPath

	if (!path) return
	if (isTabBar) {
		uni.reLaunch({
			url: path
		})
	} else {
		// #ifdef VUE2
		const { options = {} } = currPage || {}
		// #endif
		// #ifdef VUE3
		const { $page = {} } = currPage || {}
		const options = $page?.options || {}
		console.log(currPage)
		// #endif
		uni.redirectTo({
			url: path
		})
	}
}

export function compressImage(src, quality) {
	return new Promise((resolve, reject) => {
		// #ifndef H5
		uni.compressImage({
			src: src,
			quality,
			success: res => {
				resolve(res.tempFilePath)
			},
			fail: (err) => {
				reject(err)
			}
		})
		// #endif

		// #ifdef H5
		uni.getImageInfo({
			src,
			success(res) {
				console.log('压缩前', res)
				let canvasWidth = res.width // 图片原始长宽
				let canvasHeight = res.height
				let img = new Image()

				let canvas = document.createElement('canvas')
				let ctx = canvas.getContext('2d')
				// 这里根据要求限制图片宽高
				canvas.width = Math.min(1920, canvasWidth)
				canvas.height = Math.min(1080, canvasHeight)
				img.onload = () => {
					ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
					const base64 = canvas.toDataURL('image/' + res.type, quality / 10)
					resolve(base64)
					// canvas.toBlob(function(fileSrc) {
					// 	let imgSrc = window.URL.createObjectURL(fileSrc);
					// 	// 获取压缩后的图片地址，在进行上传
					// });
				}
				img.onerror = reject
				img.src = res.path
			},
			fail(err) {
				reject(err)
			}
		})
		// #endif
	})
}
